package com.fx.util;


import cn.hutool.cache.impl.TimedCache;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class CacheUtil {

    private static TimedCache<String, Object> timedCache = null;
    private static Object object = new Object();

    public static String getCacheFromRedis(JedisPool jedisPool,String key) throws Exception{
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String cacheValue = jedis.get(key);
            if(cacheValue != null && !"".equals(cacheValue)){
                return cacheValue;
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }finally {
            jedis.close();
        }
        return null;
    }

    public static void putCacheToRedis(JedisPool jedisPool,String key,Object value) throws Exception{
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            if(value != null && !"".equals(value)){
                jedis.set(key,JSONObject.toJSONString(value));
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }finally {
            jedis.close();
        }
    }

    public static TimedCache<String, Object> getTimedCache() {
        synchronized (object) {
            if (timedCache == null) {
                timedCache = cn.hutool.cache.CacheUtil.newTimedCache(Constant.CACHE_TIMEOUT);
            }
            return timedCache;
        }
    }
}
